#!/usr/bin/perl
#use strict;
#use warnings;

# get the filename to remove spacings from
my $filename = $ARGV[0];


# read in the data
open(INDATA,$filename);
my @data = <INDATA>;
close(INDATA);

# initiliase some defauls
my $MINDELTA = 0.0;
my $i=0;
my @TIME;
my @AMP;
my @iflagged;
my $n = 0;

# open the filename to write to
open(OUTDATA,">${filename}-tmp.dat");
print OUTDATA "$data[0]";
foreach my $line (@data) {
    $AMP[$i] = 0.0;
    $TIME[$i] = 0.0;
    chomp $line;
    my @Aline = split(/\s+/,$line);
    if ($Aline[0]) { # if not a blank line 
	$AMP[$i] = $Aline[1]; # reads in the amp
	$TIME[$i] = $Aline[0]; # reads in the time
	my $diff = 99.999;
	if ($i>0) {
	    # if not the first line get the difference
	    $diff = $TIME[$i]-$TIME[$i-1]; 
	}
	# if the difference is <= min specified spacing
	if ($diff <= $MINDELTA) { 
	    printf("(%d)  %.4f  %.6f %.5f *****",
		   $i,$TIME[$i],$AMP[$i], $diff); 
	    # extra condition for when the min spacing is set to > 0
	    if ($diff == 0.0) {
		print " ##"; 
	    }
	    $iflagged[$n]=$i;
	    print "  == flagged $n";
	    $n++;
	    print "\n";
	} 
	# if the difference is > specified min spacing.
	else {
	    printf("(%d)  %.4f  %.6f %.5f\n",
		   $i,$TIME[$i],$AMP[$i], $diff); 
	    printf(OUTDATA "%.4f  %.6f\n",
		   $TIME[$i],$AMP[$i]); 
	    
	}
    }
    $i++;
}
close(OUTDATA);


## in version 1 remove the first of the 2 identical times
## in version 2 remove the 2nd of the 2 identical times
my $Ndata = $i-1;
print "total points: $Ndata\n";
my $ver1 = 0.0;
my $ver2 = 0.0;
my $p = 0;
foreach $_ (@iflagged) {
    my $ver1 = $_-1; ## first of the 2 repeats
    my $ver2 = $_;   ## 2nd of the 2 repeats
    print "$p - v1:$ver1 v2:$ver2\n";
    $p++;
}

open(VER1,">${filename}-1stRemoved.dat");
open(VER2,">${filename}-2ndRemoved.dat");

$i=0;
$n=0;
foreach my $line (@data) {
    $AMP[$i] = 0.0;
    $TIME[$i] = 0.0;
    chomp $line;
    my @Aline = split(/\s+/,$line);
    if ($Aline[0]) { # if not a blank line (catches last line)
	$AMP[$i] = $Aline[1]; # reads in the amp
	$TIME[$i] = $Aline[0]; # reads in the time
	
	if ($i == $iflagged[$n]-1) {
	    print "${i} $TIME[$i] $AMP[$i] ==== removed in version 1";
	    print VER2 "$TIME[$i] $AMP[$i]\n";
	} 
	elsif ($i == $iflagged[$n]) {
	    print "${i} $TIME[$i] $AMP[$i] ++++ removed in version 2";
	    print VER1 "$TIME[$i] $AMP[$i]\n";
	    $n++;
	}
	else {
	    print "$i $AMP[$i] $TIME[$i]";
	    print VER1 "$TIME[$i] $AMP[$i]\n";
	    print VER2 "$TIME[$i] $AMP[$i]\n";
	}
	print "\n";
	$i++;
    }
}

close(VER1);
close(VER2);
